package com.liuya.safe.system.role.controller;

import com.liuya.base.BaseController;
import com.liuya.common.StringUtil;
import com.liuya.common.TypeParseUtil;
import com.liuya.common.Util;
import com.liuya.common.WebUtil;
import com.liuya.safe.model.SafeRole;
import com.liuya.safe.system.role.service.RoleManagerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;


/**
 * 角色管理
 * @author liuya
 * @date 20160826
 */
//@RestController
@Controller
@Api(value = "角色管理", description = "角色管理")
@RequestMapping(value = "rolePrivilege")
public class RolePrivilegeContrller extends BaseController{

    @Autowired
    RoleManagerService roleManagerService;

    @ApiOperation(value = "角色列表页面")
//    @RequiresPermissions("sys.queryPolicy.rawSql")
    @RequestMapping(value = "/rolePrivilege")
    public Object rolePrivilege(HttpServletRequest req, HttpServletResponse rep, ModelMap map){
        String roleId = WebUtil.getStringParameter(req, "roleId", "-23");
        SafeRole role = roleManagerService.getRole(roleId);
        Collection assignedPvlgs = roleManagerService.getPrivileges(roleId);

        req.setAttribute("role", role);
        req.setAttribute("assignedPvlgs", assignedPvlgs);

        return "system/rolePrivilege";
    }

    @ApiOperation(value = "跳转到角色添加页面")
//    @RequiresPermissions("sys.queryPolicy.rawSql")
    @RequestMapping(value = "/assignPrivileges")
    @ResponseBody
    public Object assignPrivileges(HttpServletRequest req, HttpServletResponse rep, ModelMap map){
        String roleId = WebUtil.getStringParameter(req, "roleId", "-23");
        String rawPvlgIds = req.getParameter("pvlgIds");
        String[] assignPvlgIds = StringUtil.split(rawPvlgIds, ",");
        Collection pvlgIds = TypeParseUtil.convert2Collection(assignPvlgIds);
        pvlgIds.remove("0"); // remove root node

        roleManagerService.assignPrivileges(roleId, pvlgIds);
        return true;
    }

}
